import { Injectable } from '@nestjs/common';
import { CreateMockDto } from './dto/create-mock.dto';
import { UpdateMockDto } from './dto/update-mock.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Mock } from './entities/mock.entity';
import { Repository, Like } from 'typeorm';
import { QueryMockListDto } from './dto/request-mock.dto';
import { QueryMockResponseDto } from './dto/response-mock.dto';

@Injectable()
export class MockService {
  constructor(
    @InjectRepository(Mock)
    private mockRepository: Repository<Mock>,
  ) {}

  async create(createMockDto: CreateMockDto) {
    const mock = this.mockRepository.create({
      ...createMockDto,
    });

    return await this.mockRepository.save(mock);
  }

  async findAll(query: QueryMockListDto): Promise<QueryMockResponseDto> {
    const { pathName, pageNum = 1, pageSize = 10 } = query;
    // console.log(pathName);
    const [result, total] = await this.mockRepository.findAndCount({
      where: {
        isDelete: false,
        pathName: pathName ? Like(`%${pathName}%`) : undefined,
      },
      take: pageSize,
      skip: (pageNum - 1) * pageSize,
      order: {
        id: 'DESC',
      },
    });
    return {
      data: result,
      total,
    };
  }

  async findOne(id: number) {
    const result = await this.mockRepository.findOne({
      where: {
        id,
      },
    });

    return result;
  }

  async findPathName(pathName: string) {
    const result = await this.mockRepository.findOne({
      where: {
        pathName,
      },
    });

    return result?.content
      ? (JSON.parse(result?.content) as Record<string, unknown>)
      : null;
  }

  async update(id: number, updateMockDto: UpdateMockDto) {
    const result = await this.mockRepository.update({ id }, updateMockDto);
    return result;
  }

  async remove(id: number) {
    const result = await this.mockRepository.delete(id);
    return result;
  }
}
